<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 6/30/17
 * Time: 3:03 PM
 */
declare(strict_types=1);


namespace application\module\admin\addon;

use application\module\admin\addon\model\AddonModel;
use wshore\helper\Config;
use wshore\helper\traits\Singleton;

/**
 * Class Addon 插件
 * @method  getInstance(...$params) static 获取插件实例
 * @package application\module\admin\addon
 */
abstract class Addon
{
    use Singleton;

    protected $config = [];
    /**
     * @var string
     */
    protected $error = '';

    /**
     * 返回插件名称
     * @return string
     */
    abstract protected function getName(): string;

    /**
     * Addon constructor.
     * 构造时自动加载配置
     */
    public function __construct()
    {
        $name = $this->getName();
        $cfild = WS_PATH_CONFIG . "addon/{$name}.php";
        if (is_file($cfild)) {
            $config = Config::parse($cfild);
            $this->config = array_merge($this->config, $config);
        }
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError(): string
    {
        return (string)$this->error;
    }

    /**
     * 获取配置信息
     * @param string $name
     * @return mixed|null
     */
    public function __get(string $name)
    {
        return $this->config[$name]??null;
    }

    /**
     * 设置配置值
     * @param string $name 配置项名称
     * @param string $value 配置值
     */
    public function __set(string $name, $value)
    {
        $this->config[$name] = $value;
    }

    /**
     * 返回模型列表
     * @return array
     */
    abstract protected function models(): array;

    /**
     * 安装
     * @return void
     */
    public function install()
    {
        foreach ($this->models() as $model) {
            /** @var AddonModel $model */
            $model = (new $model());
            $model->install();
        }
    }
}